package storage

import (
	"time"
	. "web_framework/model"

	"github.com/jmoiron/sqlx"
	"github.com/pkg/errors"
)

func AddUserToken(db sqlx.Ext, qi *UserToken) error {

	qi.DateLine = time.Now().Unix()

	_, err := sqlx.NamedExec(db,
		`insert into user_token(uid, token, dateline, client, registration_id) values (:uid, :token, :dateline, :client, :registration_id)`,
		*qi, )
	if err != nil {
		return err
	}

	return nil
}

func GetUserTokenCount(db sqlx.Queryer, uid int) (int, error) {

	var count int
	err := sqlx.Get(db, &count, "select count(*) from user_token where uid = ?", uid)
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetUserTokenByUidAndToken(db sqlx.Queryer, uid int, token string) (int, error) {
	var count int
	err := sqlx.Get(db, &count, "select count(*) from user_token where uid = ? and token = ?", uid, token)
	if err != nil {
		return 0, err
	}
	return count, nil
}

func GetUserToken(db sqlx.Queryer, uid int) (string, error) {
	var qi string
	err := sqlx.Get(db, &qi,
		`select token from user_token where uid = ? group by dateline asc limit 1`, uid, )
	if err != nil {
		return qi, err
	}

	return qi, nil
}

func DeleteUserToken(db sqlx.Execer, uid, limitNum int) error {
	res, err := db.Exec("DELETE FROM user_token WHERE uid = ? ORDER BY dateline ASC LIMIT ?", uid, limitNum)
	if err != nil {
		return err
	}
	ra, err := res.RowsAffected()
	if err != nil {
		return errors.Wrap(err, "get rows affected error")
	}
	if ra == 0 {
		return errors.New("not exist")
	}

	return nil
}

func DeleteUserTokenByUidToken(db sqlx.Execer, uid int, token string) error {
	res, err := db.Exec("DELETE FROM user_token WHERE uid = ? and token = ?", uid, token)
	if err != nil {
		return err
	}
	ra, err := res.RowsAffected()
	if err != nil {
		return errors.Wrap(err, "get rows affected error")
	}
	if ra == 0 {
		return errors.New("not exist")
	}
	return nil
}
